﻿Imports Aricie.DNN.UI.Controls
Imports Aricie.DNN.Modules.LuceneSearch.Business
Imports Lucene.Net.Search
Imports Lucene.Net.Index
Imports System.Linq
Imports Aricie.DNN.Modules.LuceneSearch.Settings
Imports DotNetNuke.Services.Localization
Imports Aricie.DNN.Settings


Namespace Aricie.DNN.Modules.LuceneSearch.UI
    Public Class OnlyCurrentUserItems
        Inherits LuceneFilterControlBase

        Public Property Fields As String

        Private Const userIDWhenNotChecked As String = "-1"

        Public Property FieldValue() As String
            Get
                ' Initialisation avec la valeur par défaut à -1 (correspondant à pas de filtre)
                Dim toReturn As String = userIDWhenNotChecked
                If cbxOnlyCurrentUserItems.Checked Then
                    ' Récupération de l'id de l'utilisateur courant pour filter les éléments
                    toReturn = UserId.ToString
                End If
                Return toReturn
            End Get
            Set(ByVal value As String)
                If value <> userIDWhenNotChecked Then
                    cbxOnlyCurrentUserItems.Checked = True
                Else
                    cbxOnlyCurrentUserItems.Checked = False
                End If

            End Set
        End Property

        Public Overrides Function GetFilter() As LuceneFilterQuery
            Dim toReturn As New LuceneFilterQuery

            If FieldValue <> userIDWhenNotChecked Then
                Dim fieldFilter As New BooleanQuery
                For Each Field As String In GetFieldNames()
                    fieldFilter.Add(New TermQuery(New Term(Field, FieldValue)), Occur.SHOULD)
                Next
                toReturn.FilterQuery = fieldFilter
            Else
                toReturn.FilterQuery = Nothing
            End If

            Return toReturn
        End Function

#Region "Validation du filtre"

        Private Function IsBooleanQueryValid(q As BooleanQuery) As Boolean
            For Each c As BooleanClause In q.GetClauses()
                If Not TypeOf c.Query() Is TermQuery Then
                    Return False
                End If
            Next
            Return True
        End Function

        Private Function CheckMatchingQuery(q As Query) As Boolean
            Dim Filter = Filtering.FluentFilterRulesManagerFactory.Init() _
                         .Expects(Of TermQuery)("Un seul champ") _
                         .ExpectsComplex("Plusieurs champs", AddressOf IsBooleanQueryValid) _
                         .Create()
            Return Filter.Matches(q)
        End Function

#End Region

        Public Overrides Function ParseFilter(ByVal objFilter As Business.LuceneFilterQuery) As Boolean
            If Not CheckMatchingQuery(objFilter.FilterQuery) Then
                Return False
            End If

            Dim Terms As HashSet(Of Term) = SpecificVersionLuceneProvider.Instance().CreateHashSet(Of Term)()

            SpecificVersionLuceneProvider.Instance().ExtractNativeTerm(objFilter.FilterQuery, Terms)

            Dim UserId As String = userIDWhenNotChecked

            For Each k As Term In Terms
                Dim correspondingItemFound As Boolean = False
                For Each Field As String In GetFieldNames()
                    If k.Field = Field Then
                        correspondingItemFound = True
                    End If
                Next
                If Not correspondingItemFound Then
                    Return False ' on a un champ différent de tabid, on sort immédiatement
                End If
                UserId = k.Text
            Next

            If UserId <> userIDWhenNotChecked Then
                cbxOnlyCurrentUserItems.Checked = True
            End If

            Return True
        End Function

        Public Overrides Property Enabled As Boolean
            Get
                Return cbxOnlyCurrentUserItems.Enabled
            End Get
            Set(ByVal value As Boolean)
                cbxOnlyCurrentUserItems.Enabled = value
            End Set
        End Property

        Public Overrides Function HasFilter() As Boolean
            Return (FieldValue <> userIDWhenNotChecked)
        End Function

        Public Overrides Function GetFieldNames() As System.Collections.Generic.IEnumerable(Of String)
            Dim FieldNames As IEnumerable(Of String) = PortalQueryingDriver.GetCurrent().GetSearchFields(ModuleID).Select(Of String)(Function(t) t.Id)
            If Not String.IsNullOrEmpty(Fields) Then
                FieldNames = Fields.Split(New String() {";"}, StringSplitOptions.RemoveEmptyEntries)
            End If
            Return FieldNames
        End Function

        Public Property SearchOnClick() As Boolean
            Get
                Return CBool(ViewState("SearchOnClick"))
            End Get
            Set(ByVal value As Boolean)
                If value Then
                    cbxOnlyCurrentUserItems.AutoPostBack = True
                    AddHandler cbxOnlyCurrentUserItems.CheckedChanged, AddressOf cbxOnlyCurrentUserItems_CheckedChanged
                End If
                ViewState("SearchOnClick") = value
            End Set
        End Property

        Public Sub cbxOnlyCurrentUserItems_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
            If SearchOnClick Then
                OnFilterChanged()
            End If
        End Sub


    End Class
End Namespace